package dper.study.codes.scala

import java.io.{File, PrintWriter}
import java.util.{Calendar, Date}

import scala.io.Source

/**
  * Created by leichen on 2017/8/3.
  */
object ProgramerStudy {
  def printStrs( args:String* ) = {
    var i : Int = 0
    for(arg <- args){
      println( arg + "\t" + i)
      i+=1
    }
  }

  def main(args: Array[String]): Unit = {
    var l = List("hello world","hello china","hello shanghai","hello chenlei")
    l.map(f => f.split(" ")).map{
      print
    }

    printStrs("hello world","hello china","hello shanghai")

    val date = new Date
    val logWithDateBound = log(date, _ : String)

    logWithDateBound("message1" )
    Thread.sleep(1000)
    logWithDateBound("message2" )
    Thread.sleep(1000)
    logWithDateBound("message3" )

    val str1:String = "Hello, "
    val str2:String = "Scala!"
    //柯里化(Currying)指的是将原来接受两个参数的函数变成新的接受一个参数的函数的过程。新的函数返回一个以原有第二个参数为参数的函数。
    println( "str1 + str2 = " +  strcat(str1)(str2) )


    //闭包是一个函数，返回值依赖于声明在函数外部的一个或多个变量。
    //闭包通常来讲可以简单的认为是可以访问一个函数里面局部变量的另外一个函数。

    println( "muliplier(1) value = " +  multiplier(1) )
    println( "muliplier(2) value = " +  multiplier(2) )

    val pattern = "Scala".r
    val str = "Scala is Scalable and cool"

    println(pattern findFirstIn str)
    println((pattern findAllIn str).mkString(","))
    println(pattern replaceFirstIn(str, "Java"))

    //提取器是从传递给它的对象中提取出构造该对象的参数。Scala 提取器是一个带有unapply方法的对象。unapply方法算是apply方法的反向操作：unapply接受一个对象，然后从对象中提取值，提取的值通常是用来构造该对象的值。
    //当我们在提取器对象中使用 match 语句是，unapply 将自动执行
    //通过 apply 方法我们无需使用 new 操作就可以创建对象
    val x = ProgramerStudy(5)
    println(x)

    x match
    {
      case ProgramerStudy(num) => println(x + " 是 " + num + " 的两倍！")
      //unapply 被调用
      case _ => println("无法计算")
    }



    val writer = new PrintWriter(new File("test.txt" ))

    writer.write("菜鸟教程")
    writer.close()

    Source.fromFile("test.txt" ).foreach{
      print
    }

  }
  var factor = 3
  val multiplier = (i:Int) => i * factor

  def log(date: Date, message: String)  = {
    println(date + "----" + message)
  }

  def strcat(s1: String)(s2: String) = {
    s1 + s2
  }

  def matchTest(x: Int): String = x match {
    case 1 => "one"
    case 2 => "two"
    case _ => "many"
  }

  def apply(x: Int) = x*2
  def unapply(z: Int): Option[Int] = if (z%2==0) Some(z/2) else None
}
